package com.dykj.fireFighting.server.elasticsearch.devHisWater.service.impl;

import com.dykj.fireFighting.api.elasticsearch.devHis.entity.EsDevHis;
import com.dykj.fireFighting.api.elasticsearch.devHisWater.entity.EsDevHisWater;
import com.dykj.fireFighting.api.elasticsearch.devHisWater.service.EsDevHisWaterService;
import com.dykj.fireFighting.api.elasticsearch.devHisZc.entity.EsDevHisZc;
import com.dykj.fireFighting.common.core.utils.DataCleaningUtil;
import com.dykj.fireFighting.common.core.utils.ZcDataCleaning;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.server.elasticsearch.devHis.service.impl.EsDevHisServiceImpl;
import com.dykj.fireFighting.server.elasticsearch.devHisWater.repository.EsDevHisWaterRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParser;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.ArrayList;
import java.util.List;


/**
 * Service实现类
 * Created by macro on 2018/6/19.
 */
@Slf4j
@DubboService
public class EsDevHisWaterServiceImpl implements EsDevHisWaterService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsDevHisWaterServiceImpl.class);
    @Autowired
    private EsDevHisWaterRepository esDevHisWaterRepository;

    @Override
    public EsDevHisWater importAll(EsDevHisWater esDevHisWater) {
        return esDevHisWaterRepository.save(esDevHisWater);
    }
    @Override
    public PageVo<EsDevHisWater> search(String keyword, String deviceName, Integer pageNum, Integer pageSize,String beginDate,String endDate) {
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("unitId",keyword));
        //boolQuery.must(QueryBuilders.termQuery("relationId","200727013210-4"));
        if (StringUtils.isNotBlank(deviceName)){
            boolQuery.must(QueryBuilders.wildcardQuery("deviceName","*"+deviceName+"*"));
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            boolQuery.must(QueryBuilders.rangeQuery("stateTime")
                    .from(beginDate)
                    .to(endDate)
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);

        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("stateTime").order(SortOrder.DESC));
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHisWater> search = esDevHisWaterRepository.search(searchQuery);
        PageVo<EsDevHisWater> page=new PageVo<>();
        page.setTotalCount((int)search.getTotalElements());
        page.setList(search.getContent());
        return page;
    }
    @Override
    public PageVo<EsDevHisWater> centerSearch(String keyword,String unitId, String deviceName,Integer pageNum, Integer pageSize,String beginDate,String endDate) {
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("centerUnitId",keyword));
        if(StringUtils.isNotBlank(unitId)){
            boolQuery.must(QueryBuilders.termQuery("unitId",unitId));
        }
        if (StringUtils.isNotBlank(deviceName)){
            boolQuery.must(QueryBuilders.wildcardQuery("deviceName","*"+deviceName+"*"));
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            boolQuery.must(QueryBuilders.rangeQuery("uploadTime")
                    .from(beginDate)
                    .to(endDate)
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);

        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("stateTime").order(SortOrder.DESC));
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHisWater> search = esDevHisWaterRepository.search(searchQuery);
        PageVo<EsDevHisWater> page=new PageVo<>();
        page.setTotalCount((int)search.getTotalElements());
        page.setList(search.getContent());
        return page;
    }

    @Override
    public EsDevHisWater getByRalationId(String keyword, String deviceName) {
        NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("uniqueCode",keyword))
                .withSort(SortBuilders.fieldSort("stateTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(0, 1))
                .build();
        LOGGER.info("DSL:{}", queryBuilder.getQuery().toString());
        Page<EsDevHisWater> search = esDevHisWaterRepository.search(queryBuilder);
        List<EsDevHisWater> content = search.getContent();
        if (content.size() > 0) {
            return content.get(0);
        }
        return null;

    }

    @Override
    public EsDevHisWater getByDevHisWaterId(String id) {
        NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("id",id))
                .withSort(SortBuilders.fieldSort("stateTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(0, 1))
                .build();
        LOGGER.info("DSL:{}", queryBuilder.getQuery().toString());
        Page<EsDevHisWater> search = esDevHisWaterRepository.search(queryBuilder);
        List<EsDevHisWater> content = search.getContent();
        if (content.size() > 0) {
            return content.get(0);
        }
        return null;

    }

    @Override
    public PageVo<EsDevHisWater> searchByCenterId(String centerId, String unitId, String deviceName, Integer pageNum, Integer pageSize, String beginDate, String endDate) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(centerId)) {
            boolQuery.must(QueryBuilders.termQuery("centerUnitId", centerId));
        }
        if (StringUtils.isNotBlank(unitId)) {
            boolQuery.must(QueryBuilders.termQuery("unitId", unitId));
        }
        if (StringUtils.isNotBlank(deviceName)) {
            boolQuery.must(QueryBuilders.wildcardQuery("deviceName", "*" + deviceName + "*"));
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            boolQuery.must(QueryBuilders.rangeQuery("stateTime")
                    .from(beginDate)
                    .to(endDate)
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("stateTime").order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        Page<EsDevHisWater> search = esDevHisWaterRepository.search(searchQuery);
        PageVo<EsDevHisWater> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHisWater> paggList = new ArrayList<>();
        for (EsDevHisWater e : search.getContent()){
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }
}
